<script lang="ts" setup>
import {useMemberStore} from "@/stores/member.ts";
import {ElMessage, type FormInstance, type FormRules, type UploadProps} from "element-plus";
import {onMounted, reactive, ref, watch} from "vue";
import type {MemberInfo, UpdateMember} from "@/type/member.ts";
import {resetPassword, updateMember} from "@/api/member";
import {useRouter} from "vue-router";

const memberStore = useMemberStore()
const memberInfo = ref<MemberInfo>({
  username: 'xxx',
  memberName: 'xxx',
  password: 'xxx',
  gender: 'xxx',
  height: 175,
  weight: 65,
  BMI: 20,
  contact: 'xxx',
  memberType: 'xxx',
})

// 重置密码弹窗相关
const resetPasswordDialogVisible = ref(false)
const resetPasswordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmNewPassword: '',
})
const resetPasswordFormRef = ref<FormInstance>()

// 重置密码表单验证规则
const checkInput = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('不可为空,请输入...'))
  } else {
    callback()
  }
}
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (resetPasswordForm.confirmNewPassword !== '') {
      if (!resetPasswordFormRef.value) return
      resetPasswordFormRef.value.validateField('confirmNewPassword')
    }
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== resetPasswordForm.newPassword) {
    callback(new Error("两次输入不一样!"))
  } else {
    callback()
  }
}
const rules = reactive<FormRules<typeof resetPasswordForm>>({
  oldPassword: [{validator: checkInput, trigger: 'blur'}],
  newPassword: [
    {validator: validatePass, trigger: 'blur'},
    {validator: checkInput, trigger: 'blur'}
  ],
  confirmNewPassword: [
    {validator: validatePass2, trigger: 'blur'},
    {validator: checkInput, trigger: 'blur'}
  ],
})
// 打开重置密码弹窗
const openResetPasswordDialog = () => {
  resetPasswordForm.oldPassword = ''
  resetPasswordForm.newPassword = ''
  resetPasswordForm.confirmNewPassword = ''
  resetPasswordDialogVisible.value = true
}
watch([() => memberInfo.value.height, () => memberInfo.value.weight], ([height, weight]) => {
  if (height && weight && height > 0 && weight > 0) {
    memberInfo.value.BMI = Number((weight / Math.pow(height / 100, 2)).toFixed(2));
  } else {
    memberInfo.value.BMI = 20;
  }
});
// 处理重置密码
const handleResetPassword = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        const payload = {
          memberId: memberStore.memberInfo.memberId,
          oldPassword: resetPasswordForm.oldPassword,
          newPassword: resetPasswordForm.newPassword,
        }
        // 调用接口
        const result = await resetPassword(payload)
        if (result.code == 1) {
          ElMessage.success('密码重置成功')
          resetPasswordDialogVisible.value = false
          await memberStore.memberLogout()
          await router.push('/memberLogin')
        } else {
          throw new Error(result.message)
        }
      } catch (error) {
        ElMessage.error((error as Error).message)
      }
    } else {
      ElMessage.error('检查输入')
    }
  })
}
// 获取会员信息
const getMemberInformation = async () => {
  try {
    const memberId = memberStore.memberInfo.memberId
    if (memberId !== -1) {
      const info = await memberStore.getMemberInfo(memberId)
      if (info instanceof Error) {
        ElMessage.error(info.message)
      } else {
        memberInfo.value = info
      }
    } else {
      ElMessage.error("错误数据，请稍后重试")
    }
  } catch (e) {
    ElMessage.error((e as Error).message)
  }
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
    if (rawFile.size < 4194304) {
      return true
    } else {
      ElMessage.error('上传文件必须小于 4M')
      return false
    }
  } else {
    ElMessage.error('上传文件必须是 png | img | gif')
    return false
  }
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  if (memberInfo.value) {
    memberInfo.value.avatar = response.data;
  } else {
    ElMessage.error("会员信息未加载，请稍后重试");
  }
}
// 提交表单
const submitForm = async () => {
  try {
    const updateData: UpdateMember = {
      memberId: memberStore.memberInfo.memberId,
      ...memberInfo.value,
    }
    const result = await updateMember(updateData);
    if (result.code == 1) {
      ElMessage.success('信息更新成功');
    } else {
      ElMessage.error('信息更新失败');
    }
    await getMemberInformation(); // 更新后重新获取用户信息
  } catch (error) {
    ElMessage.error('信息更新失败');
  }
}
// 重置表单
const resetForm = () => {
  getMemberInformation()
}
onMounted(() => {
  getMemberInformation()
})

const router = useRouter()
const backHome = () => {
  router.push('/member1')
}
</script>

<template>
  <div class="personal-info-container">
    <el-card class="profile-card">
      <el-button type="primary" @click="backHome" style="margin-bottom: 30px">返回首页</el-button>
      <el-form ref="memberForm" :model="memberInfo" label-width="120px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="memberInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="memberName">
          <el-input v-model="memberInfo.memberName"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="memberInfo.gender" placeholder="请选择性别">
            <el-option label="秘密" value=""/>
            <el-option label="男" value="男"/>
            <el-option label="女" value="女"/>
            <el-option label="其他" value="其他"/>
          </el-select>
        </el-form-item>
        <el-form-item label="身高(cm)" prop="height">
          <el-input-number v-model="memberInfo.height" :max="300" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="体重(kg)" prop="weight">
          <el-input-number v-model="memberInfo.weight" :max="300" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="BMI" prop="BMI">
          <el-input v-model.number="memberInfo.BMI"
                    :placeholder="((memberInfo.weight as number) / Math.pow((memberInfo.height as number) / 100, 2)).toFixed(2)"
                    disabled></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="memberInfo.contact"></el-input>
        </el-form-item>
        <el-form-item label="会员类型" prop="memberType">
          <el-input v-model="memberInfo.memberType" disabled></el-input>
        </el-form-item>
        <el-form-item label="会员起始日期" prop="membershipStartDate">
          <el-date-picker v-model="memberInfo.membershipStartDate" disabled type="date"></el-date-picker>
        </el-form-item>
        <el-form-item label="会员结束日期" prop="membershipEndDate">
          <el-date-picker v-model="memberInfo.membershipEndDate" disabled type="date"></el-date-picker>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="memberInfo.age" :max="120" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
              :before-upload="beforeAvatarUpload"
              :data="{ type: 2 }"
              :on-success="handleAvatarSuccess"
              :show-file-list="false"
              action="http://localhost:8080/files/upload"
              class="avatar-uploader">
            <img v-if="memberInfo.avatar" :src="memberInfo.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="danger" @click="openResetPasswordDialog">重置密码</el-button>
        </el-form-item>
      </el-form>
      <!-- 重置密码弹窗 -->
      <el-dialog v-model="resetPasswordDialogVisible" title="重置密码" width="30%">
        <el-form ref="resetPasswordFormRef" :model="resetPasswordForm" :rules="rules">
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input v-model="resetPasswordForm.oldPassword" show-password type="password"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="resetPasswordForm.newPassword" show-password type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmNewPassword">
            <el-input v-model="resetPasswordForm.confirmNewPassword" show-password type="password"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleResetPassword(resetPasswordFormRef)">确认</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.profile-card {
  max-width: 800px;
  margin: 20px auto;
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  :deep(.el-upload:hover) {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
}
</style>